package GestionDeDatos;

import javax.xml.soap.MessageFactory;
import javax.xml.soap.MimeHeaders;
import javax.xml.soap.SOAPConnection;
import javax.xml.soap.SOAPConnectionFactory;
import javax.xml.soap.SOAPException;
import javax.xml.soap.SOAPMessage;

import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamResult;

import Base64Coder.*;

public class ClienteSOAP {
	
	private static ClienteSOAP instancia = null;
	
	SOAPConnectionFactory soapConnFactory;
	SOAPConnection connection;
	MessageFactory messageFactory;
	
	String namespace = "nerdsmap";
	String serviceURL = "http://localhost/NerdsmapService.php";
	//String serviceURL = "http://nerdsmap.heliohost.org/NerdsmapService.php";

	
	public static ClienteSOAP Cliente() throws SOAPException {
		
		if (instancia != null) return instancia;
		
		instancia = new ClienteSOAP();
		instancia.AbrirConexion();
		return instancia;
	}
	
	private ClienteSOAP() throws SOAPException {

		soapConnFactory = SOAPConnectionFactory.newInstance();
		messageFactory = MessageFactory.newInstance();
	}

	public void AbrirConexion() throws SOAPException {
		
		connection = soapConnFactory.createConnection();
	}
	
	public void CerrarConexion() throws SOAPException {
		
		connection.close();
	}
	
	public SOAPMessage CrearMensaje() throws SOAPException {
		
		return messageFactory.createMessage();
	}
	
	public SOAPMessage EnviarMensaje(SOAPMessage mensaje) throws SOAPException {
		
		String authorization = Base64Coder.encodeString("guest:nerdsmap");
        MimeHeaders hd = mensaje.getMimeHeaders();
        hd.addHeader("Authorization", "Basic " + authorization);
        mensaje.getSOAPPart().getEnvelope().addNamespaceDeclaration(namespace, serviceURL);

        mensaje.saveChanges();
        PrintSOAPMessage(mensaje);
		SOAPMessage reply = connection.call(mensaje, serviceURL);
		PrintSOAPMessage(reply);
		
		return reply;
	}
	  
	public void PrintSOAPMessage(SOAPMessage soapMessage) throws SOAPException {
		
		try {
			System.out.println("\n");
			TransformerFactory transformerFactory = TransformerFactory.newInstance();
			Transformer transformer = transformerFactory.newTransformer();
			Source sourceContent = soapMessage.getSOAPPart().getContent();
			StreamResult result = new StreamResult(System.out);
			transformer.transform(sourceContent, result);
		} catch (TransformerException e) {};
	}
}
